import { useModel } from '@@/exports';
import { RobotFilled, RobotOutlined } from '@ant-design/icons';
import { Avatar, Button, Card, Input, message, Typography } from 'antd';

import { request } from '@/app';
import { doChatUsingPost } from '@/services/qingbi/chatMessageController';
import { useResponsive } from 'ahooks';
import React, { useEffect, useRef, useState } from 'react';

const { Search } = Input;

interface ChatMessage {
  sender: 'USER' | 'AI';
  content: string;
}

const generateRoomId = () => {
  return Math.floor(Math.random() * 1e9)
    .toString()
    .padStart(9, '0');
};
//
const HaiGuiT: React.FC = () => {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [inputText, setInputText] = useState('');
  const [loading, setLoading] = useState(false);
  const [roomId, setRoomId] = useState<string>('');
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const { baseURL } = request;
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState ?? {};
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  const searchInputRef = useRef<any>(null); // 新增：用于聚焦输入框

  const { xxl } = useResponsive(); //按钮

  const contentFontSize = useState<String>();

  const { Title, Text } = Typography;

  useEffect(() => {
    scrollToBottom();
  }, [messages]);
  // 新增：在 roomId 变化或发送消息后聚焦输入框
  useEffect(() => {
    if (roomId && searchInputRef.current) {
      searchInputRef.current.focus();
    }
  }, [roomId, messages]);

  const startGame = async () => {
    try {
      setLoading(true);
      const newRoomId = generateRoomId();
      setRoomId(newRoomId);

      // 添加用户开始消息
      setMessages((prev) => [...prev, { sender: 'USER', content: '开始' }]);

      // 发送开始请求
      const res = await doChatUsingPost({
        roomId: newRoomId,
        userPrompt: '开始',
      });

      if (res?.data) {
        setMessages((prev) => [...prev, { sender: 'AI', content: res.data }]);
      } else {
        message.error(res?.message || '游戏启动失败');
      }
    } catch (error) {
      message.error('游戏启动失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const reStartGame = async () => {
    setMessages([]); // 清空本地消息
    await startGame();
  };

  const handleSubmit = async (value: string) => {
    if (!value.trim() || loading) {
      message.error('请输入有效内容');
      return;
    }

    try {
      setLoading(true);

      // 添加用户消息
      setMessages((prev) => [...prev, { sender: 'USER', content: value }]);

      // 发送请求
      const res = await doChatUsingPost({
        roomId,
        userPrompt: value,
      });

      if (res?.data) {
        setMessages((prev) => [...prev, { sender: 'AI', content: res.data }]);
      } else {
        message.error(res?.message || '发送失败');
      }
    } catch (error) {
      message.error('发送失败，请稍后重试');
    } finally {
      setLoading(false);
      setInputText('');
    }
  };

  return (
    <div
      style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: '15px',
      }}
    >
      <Card
        title={roomId ? `房间ID: ${roomId}` : '海龟汤推理游戏'}
        headStyle={{
          fontSize: '20px',
          fontWeight: 'bold',
          textAlign: 'center',
          backgroundColor: '#1890ff',
          color: 'white',
        }}
        style={{
          width: '80%',
          maxWidth: '800px',
          borderRadius: '12px',
          boxShadow: '0 4px 8px rgba(0,0,0,0.1)',
        }}
      >
        <div
          style={{
            height: '50vh',
            overflowY: 'auto',
            padding: '16px',
            backgroundColor: '#fff',
            borderRadius: '8px',
            marginBottom: '16px',
          }}
        >
          {messages.length === 0 ? (
            <div
              style={{
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                height: '300px',
                color: '#181C18',
                textAlign: 'center',
                alignItems: 'center',
              }}
            >
              <Title level={3}>
                {' '}
                <RobotOutlined /> hi~ 我是qing智能bi的海龟汤助手
              </Title>
              <Text>你可以和我对话，畅玩海龟汤游戏，发挥你的想象力和推理能力吧 哈哈~</Text>
            </div>
          ) : null}

          {messages.map((msg, index) => (
            <div
              key={index}
              style={{
                display: 'flex',
                flexDirection: msg.sender === 'USER' ? 'row-reverse' : 'row',
                alignItems: 'center',
                margin: '12px 0',
              }}
            >
              <Avatar
                style={{
                  backgroundColor: msg.sender === 'USER' ? '#f0f0f0' : '#1890ff',
                  margin: '0 12px',
                  fontSize: '20px',
                }}
                size="large"
                src={
                  msg.sender == 'USER' ? (
                    baseURL + '/api/' + (currentUser && currentUser?.userAvatar)
                  ) : (
                    <RobotFilled />
                  )
                }
              />
              <div
                style={{
                  maxWidth: '70%',
                  padding: '12px 16px',
                  borderRadius: '12px',
                  backgroundColor: msg.sender === 'USER' ? '#1890ff' : '#f0f0f0',
                  color: msg.sender === 'USER' ? 'white' : 'rgba(0,0,0,0.85)',
                  wordBreak: 'break-word',
                }}
              >
                {msg.content}
                {msg.content.includes('【游戏已结束】') ? ( //todo 优化逻辑，当进入聊天就可以重新开始
                  <div style={{ textAlign: 'center' }}>
                    <Button
                      color="primary"
                      variant="outlined"
                      style={{ fontSize: '18px' }}
                      onClick={reStartGame}
                    >
                      重新开始
                    </Button>
                  </div>
                ) : (
                  ''
                )}
              </div>
            </div>
          ))}
          <div ref={messagesEndRef} />
        </div>

        {!roomId ? (
          <div style={{ textAlign: 'center' }}>
            <Button type="primary" size="large" onClick={startGame} loading={loading}>
              开始游戏
            </Button>
          </div>
        ) : (
          <Search
            placeholder="输入你的推理或回复"
            enterButton="发送"
            size="large"
            value={inputText}
            onChange={(e) => setInputText(e.target.value)}
            onSearch={handleSubmit}
            loading={loading}
            disabled={loading}
            allowClear
            ref={searchInputRef} //绑定聚焦事件
            autoFocus //初始状态自动聚焦
          />
        )}
      </Card>
    </div>
  );
};

export default HaiGuiT;
